package cn.good.yan.sf.t6;

import java.util.Iterator;

/**
 * 6 队列 - 基于 数组（环形数组）
 * 下标计算公式：(开始下标 + 步数) % 数组长度 = 后移后的下标;
 * 方式2：数组，容量
 *
 * @author shengren.yan
 * @create 2024-07-21
 */
public class Array2Queue<E> implements Queue<E>, Iterable<E> {

    private int head = 0;
    private int tail = 0;
    private E[] arr = null;
    private int size = 0;

    @SuppressWarnings("all")
    public Array2Queue(int num) {
        arr = (E[]) new Object[num];
    }

    // 向队列添加元素
    @Override
    public boolean offer(E e) {
        if (isFull()) {
            return false;
        }
        arr[tail] = e;
        tail = (tail + 1) % arr.length;
        size++;
        return true;
    }

    // 向队列移除元素
    @Override
    public E pool() {
        if (isEmpty()) {
            return null;
        }
        E e = arr[head];
        head = (head + 1) % arr.length;
        size--;
        return e;
    }

    // 从队列头获取值，并不移除
    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        E e = arr[head];
        return e;
    }

    // 检查队列是否为空，true就是空
    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    // 检查队列是否满了，true就是满了
    @Override
    public boolean isFull() {
        return size >= arr.length;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int n = head;
            int i = 0;

            @Override
            public boolean hasNext() {
                return i != arr.length;
            }

            @Override
            public E next() {
                E e = arr[n];
                n = (n + 1) % arr.length;
                i++;
                return e;
            }
        };
    }

    public static void main(String[] args) {
        Array2Queue<Integer> q = new Array2Queue<>(5);
        System.out.println("移除元素：" + q.pool());
        System.out.println("获取头元素：" + q.peek());
        System.out.println("添加元素：" + q.offer(1));
        System.out.println("添加元素：" + q.offer(2));
        System.out.println("添加元素：" + q.offer(3));
        System.out.println("添加元素：" + q.offer(4));
        System.out.println("添加元素：" + q.offer(5));
        System.out.println("添加元素：" + q.offer(6));
        System.out.println("添加元素：" + q.offer(7));
        System.out.println("--------------");
        for (Integer i : q) {
            System.out.println(i);
        }
        System.out.println("获取头元素：" + q.peek());
        System.out.println("移除元素：" + q.pool());
        System.out.println("移除元素：" + q.pool());
        System.out.println("移除元素：" + q.pool());
        System.out.println("移除元素：" + q.pool());
        System.out.println("--------------");
        for (Integer i : q) {
            System.out.println(i);
        }
        System.out.println("--------------");
    }

}
